﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;

namespace PSE.Framework.Process
{
    public class ProcessServiceProxy<T> : IDisposable
        where T : IProcessService
    {
        private ChannelFactory<T> _processChannel;
        private T _channel;

        public ProcessServiceProxy(Uri address)
        {
            EndpointAddress ep = new EndpointAddress(address);
            NetNamedPipeBinding binding = new NetNamedPipeBinding();
            binding.OpenTimeout = new TimeSpan(1, 0, 0);
            binding.CloseTimeout = new TimeSpan(1, 0, 0);
            binding.SendTimeout = new TimeSpan(1, 0, 0);
            binding.ReceiveTimeout = new TimeSpan(1, 0, 0);

            binding.MaxBufferPoolSize = int.MaxValue;
            binding.MaxBufferSize = int.MaxValue;
            binding.MaxReceivedMessageSize = int.MaxValue;

            binding.ReaderQuotas.MaxArrayLength = int.MaxValue;
            binding.ReaderQuotas.MaxBytesPerRead = int.MaxValue;
            binding.ReaderQuotas.MaxDepth = int.MaxValue;
            binding.ReaderQuotas.MaxNameTableCharCount = int.MaxValue;
            binding.ReaderQuotas.MaxStringContentLength = int.MaxValue;

            _processChannel = new ChannelFactory<T>(binding, ep);
            _channel = _processChannel.CreateChannel();
        }

        public T GetInstance()
        {
            return _channel;
        }

        #region IDisposable Members

        public void Dispose()
        {
            if (_processChannel != null)
            {
                // Finalizando canal
                try
                {
                    // Fecha o canal
                    if (_processChannel.State != CommunicationState.Faulted)
                        _processChannel.Close();
                }
                catch
                {
                    // Se ocorrer erro, aborta o canal
                    _processChannel.Abort();
                }

                _processChannel = null;
            }
        }

        #endregion
    }
}
